package com.listen.service.impl;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import com.listen.common.DateFormatUtil;
import com.listen.common.HttpClientUtil;
import com.listen.service.AnguanService;
import com.listen.vo.ClassParmsVO;

@Service
public class AnguanServiceImpl implements AnguanService{
	
	List<String> msgList = null;
	
	//主方法测试
	public static void main(String args[]){
		AnguanServiceImpl anguanServiceImpl = new AnguanServiceImpl();
		try {
			String code = "360102198801154824";
			String codes [] = code.split(",");
			for(int i=0;i<codes.length;i++){
				ClassParmsVO vo = new ClassParmsVO();
				vo.setTxtUserName(codes[i]);
				vo.setTxtPwd("888888");
				vo.setZY("0");
				vo.setNumBegin(52);
				vo.setNumEnd(60);//60节
				vo.setLoginurl("http://urdt.cn:9998");
				System.out.println("开始听第"+(i+1) +"/"+ codes.length +"个:"+codes[i]);
				anguanServiceImpl.updateAnguanClassStatus(vo);
				//Thread.sleep(1000*30*1);
			}
			System.out.println("全部听听完：共"+codes.length+"个");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//听课业务
	public List<String> updateAnguanClassStatus(ClassParmsVO vo){
		msgList = new LinkedList<String>();
		String name = vo.getTxtUserName();
		try {
			//1.解析综合登录页
			//getHtml(vo);
			//2.跳转至具体专业登录页
			toLoginPage(vo);
			//3.登录
			if(vo.getToLoginPageState() == 200)
				login(vo);
			else{
				String msg = "当前账户-"+ name +"-跳转至登录页面失败";
        		print(msg);
			}
			//4.修改课件状态
			listenVideos(vo);
			//退出登录
			logout(vo);
				
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msgList;
	}
	
	//解析综合登录页，获取专业登录页地址链接
	/*private void getHtml(ClassParmsVO vo) throws Exception{
		String zy = vo.getZY()==null ? "" : vo.getZY().trim();
		String loginurl = null;
        if("".equals(zy)){
        	print("未获取到听课人员相关专业信息--->ZY="+zy);
        }else{
        	Document doc = Jsoup.connect("http://urdt.cn/index_jz.html").get();
        	Elements links = doc.getElementsByTag("a");
        	for (int i = 0;i<links.size();i++) {
        		Element link = links.get(i);
        		String linkHref = link.attr("href");
        		if(Integer.parseInt(zy) == i){
        			loginurl = linkHref.substring(0,linkHref.lastIndexOf("/"));
        			vo.setLoginurl(loginurl);
                	break;
        		}
            }
        }
	}*/
	
	//根据url跳转到具体专业登录页面，并从页面抓取登录所需相关参数
	private void toLoginPage(ClassParmsVO vo) throws Exception{
		CloseableHttpResponse response = null;
		String httpUrl = vo.getLoginurl() == null ? "http://urdt.cn:9998" : vo.getLoginurl().trim();
		if("".equals(httpUrl)){
			print("三类初培专业登录页面url为空");
		}else{
			try {
				response = HttpClientUtil.getInstance().sendHttpGetResponse(httpUrl);
				int state = response.getStatusLine().getStatusCode();
				vo.setToLoginPageState(state);
				if(state == 200){
					HttpEntity entity = response.getEntity();  
					String html = EntityUtils.toString(entity);
				    Document document = Jsoup.parse(html);
				    Element parm2 = document.getElementById("__EVENTVALIDATION");
				    vo.set__eventvalidation(parm2.attr("value"));
				    Element parm3 = document.getElementById("__VIEWSTATE");
				    vo.set__viewstate(parm3.attr("value"));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				HttpClientUtil.getInstance().closeResource(response);
			}
		}
	}
	
	//根据用户名、密码、专业类型，登录听课网页
	private void login(ClassParmsVO vo) throws Exception{
		CloseableHttpResponse response = null;
		Map<String, String> maps = new HashMap<String, String>();
        maps.put("__VIEWSTATE", vo.get__viewstate()); 
        maps.put("__EVENTVALIDATION",vo.get__eventvalidation()); 
        maps.put("txtUserName",vo.getTxtUserName());
        maps.put("txtPwd",vo.getTxtPwd());
        maps.put("ddlType", "2");//学员登录 
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        try {
        	HttpPost httpPost = new HttpPost(vo.getLoginurl());// 创建httpPost
        	httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        	httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        	response = HttpClientUtil.getInstance().sendHttpPost(maps,httpPost);
        	int state = response.getStatusLine().getStatusCode();
        	vo.setLoginState(state);
        	if(state==302 || state==200){
        		//System.out.println("state:"+state+",登录成功!");
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		String sessionIds = hearders[0].getValue();
        		String sessionId = sessionIds.substring(0, sessionIds.indexOf(";") + 1);
        		vo.setSessionId(sessionId);
        		String userIdCookie = hearders[1].getValue();
        		String userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
        		vo.setUserid(userid);
        		String infoCookies = hearders[2].getValue();
        		String info = infoCookies.substring(0, infoCookies.indexOf(";") + 1);
        		vo.setInfo(info);
        	}else{
        		System.out.println("账号-"+vo.getTxtUserName()+"-登录失败，请检查该号码是否开通");
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//网络初次培训平台听课
	private boolean listenVideos(ClassParmsVO vo){
		CloseableHttpResponse response = null;
		int numBegin = vo.getNumBegin();
		int numEnd = vo.getNumEnd();
		String name = vo.getTxtUserName();
		String userid = vo.getUserid();
		String sessionid = vo.getSessionId();
		String info = vo.getInfo();
		String checkUid = userid.split("=")[1];
		boolean b = true;
		for (int i = numBegin; i <= numEnd; i++) {
			try {
				Thread.sleep(3000);
				String rvCode = i < 10 ? "0000" + i : "000" + i;
				int number = (int)(40+Math.random()*(80-40+1));
				String Start = DateFormatUtil.getDateAnyMinuteBeforeStr(number);
				Start = Start.replaceAll(" ", "+").replaceAll(":", "%3a");
				String cookies = sessionid + userid + info + " id="+ rvCode +"; checkUid="
						+ checkUid + " Start="+ Start +";st=0001/1/1%200%3A00%3A00" + "PC1=%u6210%u529F;totaltime=2465;PC2=%u6210%u529F;PC3=%u6210%u529F;PC4=%u6210%u529F;nowtime=2465";
				String updateUrl = vo.getLoginurl() + "/EntpClass/Xtyl1.ashx?classid="+i+"&uid="+checkUid;
				HttpPost httpPost = new HttpPost(updateUrl);// 创建httpPost
				httpPost.setHeader("X-Requested-With","XMLHttpRequest");
				httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
				httpPost.setHeader("Accept","application/json");
				httpPost.setHeader("Cookie", cookies);
				response = HttpClientUtil.getInstance().sendHttpPost(httpPost);
				int state = response.getStatusLine().getStatusCode();
				String msg = EntityUtils.toString(response.getEntity(), "UTF-8");
				System.out.println("msg="+msg);
	        	//String msg = (String) JSONObject.fromObject(entityStr).get("d");
				if(state == 200){
					print("账号-"+ name +" 第"+i +"个视频"+msg + " state="+state);
				}else{
					print("账号-"+ name +" 第"+i +"个视频"+msg + " state="+state);
					if(i != 60)//不是最后一个
						b = false;
					break;
				}
				vo.setUpdateClassMsg(msg);
			} catch (Exception e) {
				b = false;
				e.printStackTrace();
			}finally{
				HttpClientUtil.getInstance().closeResource(response);
			}
		}
		return b;
	}
	
	//最终提交链接
	/*private boolean listenVideosTwo(ClassParmsVO vo){
		return true;
	}*/
	
	
	//退出登录
	private void logout(ClassParmsVO vo){
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		String userid = vo.getUserid();
		String sessionid = vo.getSessionId();
		String info = vo.getInfo();
		try {
			String path = vo.getLoginurl() + "/Public/Logout.aspx";
			httpGet = new HttpGet(path);
			String cookie = sessionid + userid + info + " totaltime=2281; checkUid=38060; nowtime=2281";
			httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			httpGet.setHeader("Cookie", cookie);
			response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200 || state == 302){
				print("账号："+ vo.getTxtUserName() +" 退出登录成功!");
			}else{
				print("账号："+ vo.getTxtUserName() +" 退出登录失败!");
			}
		} catch (Exception e) {
			print("账号："+ vo.getTxtUserName() +" 退出登录失败--->"+e);
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	private void print(String msg){
		msgList.add(msg);
		System.out.println(msg);
	}
}
